<template>
    <div >
        <el-container>
            <el-aside style="background-color: white;height:92.6vh" width="11vw">
              <el-scrollbar>
                <el-menu default-active="全部商品" @select="handleSelect">
                  <el-menu-item index="全部商品" style="border-bottom: 1px solid #c5c5c5;">
                    <span>全部商品</span>
                  </el-menu-item>
                  <el-menu-item v-for="type in typeList" :key="type.typeId" :index="type.goodsType" style="border-bottom: 1px solid #c5c5c5;">
                    <span>{{type.goodsType}}</span>
                  </el-menu-item>
                </el-menu>
              </el-scrollbar>
            </el-aside>

            <el-main>
              <div>
                <el-row justify="space-between">
                  <el-col :span="6">
                    <el-radio-group v-model="option" size="large">
                      <el-radio-button label="all">全部</el-radio-button>
                      <el-radio-button label="new">新品</el-radio-button>
                      <el-radio-button label="hot">热销</el-radio-button>
                      <el-radio-button label="lay">滞销</el-radio-button>
                    </el-radio-group>
                  </el-col>
                  <el-col :span="8">
                    <el-row v-if="store.auth!==3">
                      <el-button :icon="Plus" round size="large" @click="showAddGoodsStore">新增</el-button>
                      <el-upload
                          ref="upload"
                          :limit="1"
                          :auto-upload="true"
                          :http-request="importGoods"
                          :show-file-list="false"
                      >
                        <template #trigger>
                          <el-button round size="large" >导入商品</el-button>
                        </template>
                      </el-upload>

                      <el-button round size="large" @click="exportGoods">导出商品</el-button>
                    </el-row>
                  </el-col>

                  <el-col :span="10" style="text-align: right">
                    <el-input
                        v-model="searchValue"
                        placeholder="输入名称或条码"
                        :prefix-icon="Search"
                        style="max-width: 20vw"
                        size="large"
                    />
<!--                      <el-button size="large" @click="search">搜索</el-button>-->
                  </el-col>


                </el-row>

              </div>
              <div style="margin-top: 2vh" v-loading="isLoading">
                <el-table :data="tableData(search(curGoodsStoreList))"
                          height="74vh"
                          style="width: 100%;"
                          :header-cell-style="tableHeaderColor"
                          @selection-change="handleSelectionChange"
                >
                    <el-table-column type="selection"  />
                    <el-table-column label="商品名/条码" width="300">
                        <template #default="scope">
                            <el-row align='middle'>
                                <el-col span="5">
                                    <el-image :src="scope.row.image" style="height: 70px;">
                                        <template #error>
                                            <div class="image-slot">
                                                <el-icon><Picture /></el-icon>
                                            </div>
                                        </template>
                                    </el-image>
                                </el-col>
                                <el-col span="19" style="padding-left: 5%;">
                                    <el-row style="max-width: 145px"><el-text>{{ scope.row.goodsName }}</el-text></el-row>
                                    <el-row><el-text>{{ scope.row.code }}</el-text></el-row>
                                </el-col>
                            </el-row>
                        </template>
                    </el-table-column>
                    <el-table-column prop="cost" label="成本价" />
                    <el-table-column prop="price" label="零售价" />
                    <el-table-column label="毛利率" >
                        <template #default="scope">
                            <el-text>{{getGrossRate(scope.row.price,scope.row.cost)}}%</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column prop="creationDate" label="已售天数" v-if="option==='new'">
                        <template #default="scope">
                            <el-text>{{getDaysBetween(scope.row.creationDate)}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="最近售出时间" width="130" v-if="option==='lay'">
                        <template #default="scope">
                            <el-text>{{scope.row.latestSellingTime===null?"从未销售":getFormatDate(scope.row.latestSellingTime)}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="近30天销售量" width="130" v-if="option!=='all'">
                        <template #default="scope">
                            <el-text>{{scope.row.salesNum}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="近30天销售额" width="130" v-if="option!=='all'">
                        <template #default="scope">
                            <el-text>{{scope.row.salesVolume}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="近30天毛利额" width="130" v-if="option!=='all'">
                        <template #default="scope">
                            <el-text>{{scope.row.gross}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="销售笔数" v-if="option!=='all'">
                        <template #default="scope">
                            <el-text>{{scope.row.transactionsNum}}</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope">
                            <el-button :disabled="store.auth===3"  @click="handleEdit(scope.row)"
                            >编辑</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
                  <div style="justify-content: center;align-items:center;height: 60px; background-color: rgba(255,255,255,0.72);boxShadow:1px 0px 1px #a6a6a6;z-index: 999;display: flex;padding: 5px 25px 5px 25px;">
                      <div style="flex: 1">
                          <el-button
                                  size="large"
                                  v-if="store.auth!==3"
                                  round
                                  @click="multipleSelection.length!==0?delShow=true:ElMessage({message: '请先选中商品', type: 'warning', })">
                              删除选中
                          </el-button>
                      </div>
                      <div style="flex: 4;" >
                          <el-pagination
                                  v-model:current-page="currentPage"
                                  v-model:page-size="pageSize"
                                  :background="true"
                                  layout="->,prev, pager, next, jumper"
                                  :total="search(curGoodsStoreList).length"
                                  @current-change="handleCurrentChange"
                          />
                      </div>
                  </div>
              </div>
            </el-main>

        </el-container>
    </div>

    <el-dialog v-model="delShow" title="确定删除选中商品吗"  width="30%" center>
        <div style="text-align: center">
        <el-button @click="delShow = false">取消</el-button>
        <el-button type="danger" @click="delSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>

  <AddGoodsStore ref="addGoodsStore" @confirmAdd="confirmAdd"/>
  <UpdateGoodsStore ref="updateGoodsStore" @confirmUpdate="confirmUpdate"/>
</template>

<script setup>
import {
    Plus,
    Search,
    Picture
} from '@element-plus/icons-vue'
import {onMounted, ref, watch} from "vue";
import {store} from "@/store";
import request from "@/utils/request";
import {dateTimeUtils} from "@/utils/dateTimeUtils";
import {ElMessage} from "element-plus";
import AddGoodsStore from "@/components/goods/AddGoodsStore";
import {put} from "@/utils/OSS";
import {exportExcel} from "@/utils/excelExportUtils";
import UpdateGoodsStore from "@/components/goods/UpdateGoodsStore.vue";


let typeList=ref([])
let goodsStoreList=ref([])
let curGoodsStoreList=ref([])
const curType=ref("全部商品")
const option=ref("all")
const searchValue=ref("")
const multipleSelection=ref([])
let delShow=ref(false)
const currentPage = ref(1)
const pageSize = ref(30)
const addGoodsStore=ref()
const updateGoodsStore=ref()
const upload = ref()
let timer=ref()
let timer2=ref()
onMounted(()=>{
  isLoading.value=true
    timer = setInterval(() => {
        console.log(2,store.goodsDone)
        if(store.goodsDone){
            request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                store.goodsStoreInfoList=[]
                for (let i in res.data){
                    // timer2 = setInterval(() => {
                    //     if (store.getLocalStorage(res.data[i])!=null){
                            store.goodsStoreInfoList.push(store.getLocalStorage(res.data[i]))
                            // clearInterval(timer2)
                        // }
                    // }, 1000);

                    // console.log(store.getLocalStorage(res.data[i]))
                }
                goodsStoreList.value=store.goodsStoreInfoList
                curGoodsStoreList.value=goodsStoreList.value
              isLoading.value=false
                // console.log(curGoodsStoreList.value)
                clearInterval(timer)
            })
        }

    }, 1000);
  // setTimeout(()=>{
  //   request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
  //     store.goodsStoreInfoList=[]
  //     for (let i in res.data){
  //       store.goodsStoreInfoList.push(store.getLocalStorage(res.data[i]))
  //     }
  //     goodsStoreList.value=store.goodsStoreInfoList
  //     curGoodsStoreList.value=goodsStoreList.value
  //   })
  // },1000)
  request.get("/goods/get/typeList").then(res=>{
    typeList.value=res.data
  })
})

const handleSelect = (key) => {
  curType.value=key
  curGoodsStoreList.value=filList(key,goodsStoreList.value)
}

const filList = (key,list) => {
  if (key==="全部商品")
    key=""
  // 返回过滤后的数组
  return list.filter((p)=>{
    return p.goodsType.indexOf(key) !==-1
  })
}

let isLoading=ref(false);
watch(option, (n, o) => {
  if (n==="all"){
    goodsStoreList.value=store.goodsStoreInfoList
    curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
  }
  if (n==="new"){
    isLoading.value=true
    request.get("/goods/get/newGoodsStore/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
      goodsStoreList.value=res.data
      curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
      isLoading.value=false
    })
  }
  if (n==="hot"){
    isLoading.value=true
    request.get("/goods/get/goodsHotSale/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
      goodsStoreList.value=res.data
      curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
      isLoading.value=false
    })
  }
  if (n==="lay"){
    isLoading.value=true
    request.get("/goods/get/goodsUnsalable/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
      goodsStoreList.value=res.data
      curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
      isLoading.value=false
    })
  }
})

function  getDaysBetween(date){
    const startDate = Date.parse(date);
    const endDate = new Date();
    if (startDate>endDate){
        return 0;
    }
    if (startDate===endDate){
        return 1;
    }
    let days=(endDate - startDate) / (24 * 60 * 60 * 1000)
    if (days===0)
        days=1
    return Math.ceil(days);
}
function getGrossRate(price,cost) {
    return (((price-cost)/price).toFixed(2)*100).toFixed(0)
}

function getFormatDate(date) {
    const formatDate=dateTimeUtils.getDate(date)
    return formatDate.year+"-"+formatDate.month+"-"+formatDate.day
}

const handleSelectionChange = (val) => {
    multipleSelection.value = val
    console.log(multipleSelection.value)
}

const delSubmit = () => {
    let delGoodsStoreBo={
        storeId:store.getLocalCurrentStoreMain().storeId,
        codeList:[]
    }
    for (let i in multipleSelection.value){
        delGoodsStoreBo.codeList.push(multipleSelection.value[i].code)
    }

    request.post("/goods/del/goodsStore",delGoodsStoreBo).then(res=>{
        if (res.code===200){
            for (let i in delGoodsStoreBo.codeList){
                localStorage.removeItem(delGoodsStoreBo.codeList[i])
            }
            request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                store.goodsStoreInfoList=[]
                for (let i in res.data){
                    store.goodsStoreInfoList.push(store.getLocalStorage(res.data[i]))
                }
                if (option.value==="all"){
                    goodsStoreList.value=store.goodsStoreInfoList
                    curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
                }
                if (option.value==="new"){
                    request.get("/goods/get/newGoodsStore/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                        goodsStoreList.value=res.data
                        curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
                    })
                }
                if (option.value==="hot"){
                    request.get("/goods/get/goodsHotSale/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                        goodsStoreList.value=res.data
                        curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
                    })
                }
                if (option.value==="lay"){
                    request.get("/goods/get/goodsUnsalable/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                        goodsStoreList.value=res.data
                        curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
                    })
                }
                ElMessage({
                    message: '已删除选中商品',
                    type: 'success',
                })
                delShow.value=false
            })

        }
    })
}

const handleCurrentChange = (e) => {
    currentPage.value = e;
};
const tableData = (list) => {
    return list.filter(
        (item, index) =>
            index < currentPage.value * pageSize.value &&
            index >= pageSize.value * (currentPage.value - 1)
    );
};

const search = (list) => {
    console.log(list)
    let reList=[]
    if (list.length!==0&&list[0]===null){
        // timer2 = setInterval(() => {
        //     console.log(curGoodsStoreList.value)
        //     if (curGoodsStoreList.value[0]!==null){
        //         reList= curGoodsStoreList.value.filter((p)=>{
        //             return p.goodsName.indexOf(searchValue.value) !==-1 || p.code.indexOf(searchValue.value) !==-1
        //         })
        //         clearInterval(timer2)
        //         return reList
        //     }
        // }, 500);
        return reList

    }else {
        return list.filter((p)=>{
            return p.goodsName.indexOf(searchValue.value) !==-1 || p.code.indexOf(searchValue.value) !==-1
        })
    }
}

const showAddGoodsStore = () => {
  addGoodsStore.value.show()
}

const confirmAdd = () => {
    ElMessage({
        message: '已新增',
        type: 'success',
    })
  request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res1=>{
    for (let i in res1.data){
      localStorage.removeItem(res1.data[i])
    }
    request.get("/goods/get/goodsInfo/"+store.getLocalCurrentStoreMain().storeId).then(res2=>{
      for (let i in res2.data){
        store.setLocalStorage(res2.data[i].code,res2.data[i])
      }
      store.resetStoreGoodsInfo()
      console.log("resetLocalGoodsInfo done")
      store.goodsStoreInfoList=[]
      for (let i in res1.data){
        store.goodsStoreInfoList.push(store.getLocalStorage(res1.data[i]))
      }
      if (option.value==="all"){
        goodsStoreList.value=store.goodsStoreInfoList
        curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
      }
      if (option.value==="new"){
        request.get("/goods/get/newGoodsStore/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
          goodsStoreList.value=res.data
          curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
        })
      }
      if (option.value==="hot"){
        request.get("/goods/get/goodsHotSale/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
          goodsStoreList.value=res.data
          curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
        })
      }
      if (option.value==="lay"){
        request.get("/goods/get/goodsUnsalable/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
          goodsStoreList.value=res.data
          curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
        })
      }
    })
  })
}

const confirmUpdate = () => {
    console.log("已修改")
    ElMessage({
        message: '已修改',
        type: 'success',
    })
    request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res1=>{
        for (let i in res1.data){
            localStorage.removeItem(res1.data[i])
        }
        request.get("/goods/get/goodsInfo/"+store.getLocalCurrentStoreMain().storeId).then(res2=>{
            for (let i in res2.data){
                store.setLocalStorage(res2.data[i].code,res2.data[i])
            }
            store.resetStoreGoodsInfo()
            console.log("resetLocalGoodsInfo done")
            store.goodsStoreInfoList=[]
            for (let i in res1.data){
                store.goodsStoreInfoList.push(store.getLocalStorage(res1.data[i]))
            }
            if (option.value==="all"){
                goodsStoreList.value=store.goodsStoreInfoList
                curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
            }
            if (option.value==="new"){
                request.get("/goods/get/newGoodsStore/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                    goodsStoreList.value=res.data
                    curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
                })
            }
            if (option.value==="hot"){
                request.get("/goods/get/goodsHotSale/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                    goodsStoreList.value=res.data
                    curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
                })
            }
            if (option.value==="lay"){
                request.get("/goods/get/goodsUnsalable/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                    goodsStoreList.value=res.data
                    curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
                })
            }
        })
    })
}

const importGoods = (e) => {
  put("Excel/"+store.getLocalCurrentStoreMain().storeId+".xlsx",e.file).then(res=>{
    request.post("/goods/importExcel",{
      storeId:store.getLocalCurrentStoreMain().storeId,
      excelFileName:res.name
    }).then(res=>{
      if (res.code===200){
        ElMessage({
          message: '导入成功',
          type: 'success',
        })
        request.get("/goods/get/goodsCodeList/"+store.getLocalCurrentStoreMain().storeId).then(res1=>{
          for (let i in res1.data){
            localStorage.removeItem(res1.data[i])
          }
          request.get("/goods/get/goodsInfo/"+store.getLocalCurrentStoreMain().storeId).then(res2=>{
            for (let i in res2.data){
              store.setLocalStorage(res2.data[i].code,res2.data[i])
            }
            store.resetStoreGoodsInfo()
            console.log("resetLocalGoodsInfo done")
            store.goodsStoreInfoList=[]
            for (let i in res1.data){
              store.goodsStoreInfoList.push(store.getLocalStorage(res1.data[i]))
            }
            if (option.value==="all"){
              goodsStoreList.value=store.goodsStoreInfoList
              curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
            }
            if (option.value==="new"){
              request.get("/goods/get/newGoodsStore/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                goodsStoreList.value=res.data
                curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
              })
            }
            if (option.value==="hot"){
              request.get("/goods/get/goodsHotSale/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                goodsStoreList.value=res.data
                curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
              })
            }
            if (option.value==="lay"){
              request.get("/goods/get/goodsUnsalable/"+store.getLocalCurrentStoreMain().storeId).then(res=>{
                goodsStoreList.value=res.data
                curGoodsStoreList.value=filList(curType.value,goodsStoreList.value)
              })
            }
          })
        })
      }else {
        ElMessage({
          message: res.message,
          type: 'error',
        })
      }

    })
  })
}

const exportGoods = () => {

  exportExcel(store.goodsStoreInfoList,store.getLocalCurrentStoreMain().storeId+"_exportGoods",
      ['商品条形码','商品标题','库存','进货价','零售价','预警库存'],"sheet")
}

const handleEdit = (data) => {
  updateGoodsStore.value.show(data)
}

const tableHeaderColor = () => {
  return { background: "#f6f6f6",  }
}
</script>

<style scoped>
.el-menu-item.is-active {
  color: rgb(46, 126, 226) !important;
  font-weight: bold;
  border-right: 2px solid rgb(47, 125, 223);
}
.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}
</style>